package cn.ylg.com.draglayouthelperdemo;

import android.content.Context;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

/**
 * Created by MyPC on 2016/10/26.
 */
public class DragLayout extends LinearLayout {
    private static final float SENSIVITY = 1.0f;
    View small_view;//应该等到布局绘制成功在findid;
    private  ViewDragHelper dragHelper;
    public DragLayout(Context context) {
        this(context,null);
    }

    public DragLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        dragHelper=ViewDragHelper.create(this,SENSIVITY,new DragHelperCallback());
    }


    //布局绘制完成调用;
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        small_view = findViewById(R.id.small_view);
    }

    private class DragHelperCallback extends ViewDragHelper.Callback{
        /*判断当前选择的空间是否允许滚动*/
        @Override
        public boolean tryCaptureView(View child, int pointerId) {

            return small_view==child;
        }

        /**
         *
         * @param child 可以水平拖拽的view
         * @param left 距离left的位置
         * @param dx
         * @return
         */
        @Override
        public int clampViewPositionHorizontal(View child, int left, int dx) {

            int leftBound = 0+ getPaddingLeft();
            int rightBound = getWidth() - small_view.getWidth();
            return Math.min(Math.max(left, leftBound), rightBound); // 返回新的left 位置
        }

        @Override
        public int clampViewPositionVertical(View child, int top, int dy) {
            int topBOund = getPaddingTop();
            int bottomBound = getHeight() - small_view.getHeight();
            return Math.min(Math.max(top, topBOund), bottomBound);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        dragHelper.processTouchEvent(event);// 让dragerhelper把当前的事件给处理
        return true;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        int action = MotionEventCompat.getActionIndex(ev);
        /*如果当前拖拽的操作已经不搞了（用户手指抬起。。。）， 通知draghelper*/
        if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
            dragHelper.cancel();
            return  false;
        }
        return super.onInterceptTouchEvent(ev);
    }
}
